package socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在链接客户端");
            socket = new Socket("localhost", 8088);//176.201.111.15
            System.out.println("链接成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public  void start(){
        System.out.println("请输入内容:");
        Scanner scanner = new Scanner(System.in);
        try {
            OutputStream out = socket.getOutputStream();
            while (true){
                String line = scanner.nextLine();
                if ("exit".equals(line)){
                    break;
                }else{
                    byte[] data = line.getBytes(StandardCharsets.UTF_8);
                    out.write(data.length);
                    out.write(data);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
